package com.crm.customers.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.crm.customers.dao.ApproveItemDao;
import com.crm.customers.dao.ApproveItemUserDao;
import com.crm.customers.model.ApproveItem;
import com.crm.customers.model.ApproveItemUser;
import com.crm.customers.model.Commission;
import com.crm.customers.model.ContractBill;
import com.crm.customers.model.ContractMoneylog;
import com.crm.customers.model.ContractUpdateHistory;
import com.crm.customers.model.Paid;
import com.crm.customers.service.ApproveItemService;
import com.crm.customers.service.CommissionService;
import com.crm.customers.service.ContractBillService;
import com.crm.customers.service.ContractMoneylogService;
import com.crm.customers.service.ContractUpdateHistoryService;
import com.crm.customers.service.PaidService;
import com.crm.im.core.model.Message;
import com.crm.sys.model.ApproveConfigure;
import com.crm.sys.service.PushService;
import com.crm.user.service.UserService;
import com.crm.util.Constants;
@Service("approveItemService")
public class ApproveItemServiceImpl implements ApproveItemService {
	@Autowired
	private ApproveItemDao approveItemDao;
	@Autowired
	private ApproveItemUserDao approveItemUserDao;
	@Autowired
	private ContractMoneylogService contractMoneylogService;
	@Autowired
	private PushService pushService;
	@Autowired
	private ContractBillService contractBillService;
	@Autowired
	private UserService userService;
	@Autowired
	private CommissionService commissionService;
	@Autowired
	private ContractUpdateHistoryService contractUpdateHistoryService;
	@Autowired
	private PaidService paidService;
	
	@Override
	public void saveApprove(ApproveConfigure config, Long fkid,Long urlId,Long uid, String name) throws Exception {
		//添加审批项
		ApproveItem approveItem = new ApproveItem();
		approveItem.setFkid(fkid);
		approveItem.setName(name);
		approveItem.setState(Constants.ApproveState.ONE);//默认审批中
		approveItem.setName(name+config.getRemark());
		approveItem.setUrl(config.getUrltemplate().replace("{param}", urlId.toString()));
		approveItem.setType(config.getType());
		approveItem.setCreateuser(uid);
		ApproveItem  resultObj = approveItemDao.insertSelective(approveItem);
		if(resultObj.getId()!=null){
			//循环插入审批人
			List<ApproveItemUser>  userItem = config.getItem();
			int i = 0;
			for(ApproveItemUser user:userItem){
				if(i==0){
					user.setState(Constants.ApproveState.ONE);//第一条记录 设置为审批中
					//及时通讯 通知审批人已有新审批项
					String msg = approveItem.getName()+"  需要你审批";
					Message message = new Message();
					message.setType("2");
					message.setContent(msg);
					message.setReceiver(String.valueOf(user.getUid()));
					pushService.pushMsgToUser(message);
					userService.sendMsgToQQ(user.getUid(), msg);
				}else{
					user.setState(Constants.ApproveState.ZERO);//其它设置为待审批
				}
				user.setAiid(resultObj.getId());//设置审批项ID 
				approveItemUserDao.insertSelective(user);
				i++;
			}
		}else
		{
			throw new Exception("审批项插入失败 提交spring 回滚");
		}
		
	}

	@Override
	public List<ApproveItem> getApproveItemAll(ApproveItem item, int pageNo , int pageSize) {
		item.setStartsize((pageNo-1)*pageSize);
		item.setEndsize(pageSize);
		return approveItemDao.selectApproveListByParam(item);
	}

	@Override
	public List<ApproveItem> getMyItemAll(ApproveItem item, int pageNo,
			int pageSize) {
		item.setStartsize((pageNo-1)*pageSize);
		item.setEndsize(pageSize);
		return approveItemDao.selectMyListByParam(item);
	}

	@Override
	public int saveAgreeApprove(ApproveItem ai) {
		//判断审批内容是否存在 且在审批中的
		ApproveItem   approveItem = approveItemDao.selectByPrimaryKey(ai.getId());
		int result =0;//默认失败
		int approveState = ai.getState();//审批状态
		int approveType = approveItem.getType();//审批类型
		if(approveItem!=null&&approveItem.getId()>0&&approveItem.getState()==Constants.ApproveState.ONE){
			ApproveItemUser  approveuser = new ApproveItemUser();
			approveuser.setAiid(ai.getId());
			approveuser.setUid(ai.getCreateuser());
			approveuser.setState(Constants.ApproveState.ONE);
			approveuser.setIsnew(1);//最新审批用户
			ApproveItemUser  au = approveItemUserDao.selectCurrentApproveUser(approveuser);
			//最新审批用户存在执行
			if(au!=null&&au.getId()!=null){
				//更新当前用户审批状态
				ApproveItemUser  approve = new ApproveItemUser();
				approve.setId(au.getId());
				approve.setState(ai.getState());
				approve.setUid(au.getUid());
				approve.setOpinion(ai.getRemark());//审批意见
				approveItemUserDao.updateByPrimaryKeySelective(approve);
				String msg ="";
				//状态(0 待审批 1 审批中  2 通过  3 驳回   4 完成)  
				if(approveState==Constants.ApproveState.TOW){	
					//判断有没有下一审批用户
					ApproveItemUser nexau = approveItemUserDao.selectNextApproveUser(au);
					//有下一用户 更新下一用户为审批中
					if(nexau!=null&&nexau.getId()!=null){
						approve = new ApproveItemUser();
						approve.setId(nexau.getId());
						approve.setState(Constants.ApproveState.ONE);//设置下一审批用户为审批中
						result = approveItemUserDao.updateByPrimaryKeySelective(approve);
						msg =approveItem.getName()+"  需要你审批";
						Message message = new Message();
						message.setContent(approveItem.getName()+"  需要你审批");
						message.setReceiver(String.valueOf(nexau.getUid()));
						pushService.pushMsgToUser(message);
						userService.sendMsgToQQ(nexau.getUid(), msg);
					}else{
						//审批通过
						result = updateApproveState(approveItem.getFkid(), approveItem.getId(), approveState, approveType);
						msg = approveItem.getName()+"已审批通过";
						//通知审批人 审批项通过
						Message message = new Message();
						message.setContent(msg);
						message.setReceiver(String.valueOf(approveItem.getCreateuser()));
						pushService.pushMsgToUser(message);
						userService.sendMsgToQQ(approveItem.getCreateuser(), msg);
					}
				}else if(approveState==Constants.ApproveState.THREE){
					//审批驳回
					result = updateApproveState(approveItem.getFkid(), approveItem.getId(), approveState, approveType);
					msg = approveItem.getName()+"被驳回<br>驳回理由：" +ai.getRemark();
					//通知审批人 审批项被驳回
					Message message = new Message();
					message.setContent(msg);
					message.setReceiver(String.valueOf(approveItem.getCreateuser()));
					pushService.pushMsgToUser(message);
					
					userService.sendMsgToQQ(approveItem.getCreateuser(), msg);
				} 
			} 
		}
		return result;
	}
	
	
	/**
	 *  更新内容审批状态  
	 * @param id   内容ID
	 * @param itemId   审批项ID
	 * @param state   审批状态
	 * @param type   类型   0  付款    1 收款   2 发票
	 * @return
	 */
	private int updateApproveState(Long id,Long itemId,int state,int type){
		int result =0;
		//更新审批项状态为已完成
		ApproveItem  approveItem = new ApproveItem();
		approveItem.setId(itemId);
		approveItem.setState(Constants.ApproveState.FOUR);
		approveItemDao.updateByPrimaryKeySelective(approveItem);
		//判断审批流
		switch (type) {
		case 0:
			//付款审批状态更新
			ContractMoneylog cmpay = new ContractMoneylog();
			cmpay.setId(id);
			cmpay.setApprovalstatus(state);
			result =contractMoneylogService.updateContractMoneylogApproveState(cmpay);
			break;
		case 1:
			//收款状态更新
			ContractMoneylog cmsk = new ContractMoneylog();
			cmsk.setId(id);
			cmsk.setApprovalstatus(state);
			result =contractMoneylogService.updateContractMoneylogApproveState(cmsk);
			 
			break;
		case 2:
			//发票审批 待定
			ContractBill cb = new ContractBill();
			cb.setId(id);
			cb.setApprovalstatus(state);
			result = contractBillService.updataContractBillApproveState(cb);
			break; 
		case 3:
			//代办审批
			Commission c = new Commission();
			c.setId(id);
			c.setApprovestate(state);
			result = commissionService.updateCommissionApprovestate(c);
			break;
		case 4:
			//合同修改审批
			ContractUpdateHistory cuh = new ContractUpdateHistory();
			cuh.setId(id);
			cuh.setAppstate(state);
			cuh.setType(null);
			result = contractUpdateHistoryService.updateHistyory(cuh);
			break;
		case 5:
			//报销审批
			Paid paid = new Paid();
			paid.setId(id);
			paid.setApprovestate(state);
			result = paidService.updatePaidApprovestate(paid);
			break;
		} 
		return result;
		
	}

	@Override
	public List<ApproveItemUser> selectApproveUserByFkid(ApproveItem ai) {
		return approveItemUserDao.selectApproveUserByFkid(ai);
	}
	
	 
 
}
